//
//  FIPTemperatureVC.m
//  fireplace
//
//  Created by XiangDongMBP on 2017/3/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "FIPTemperatureVC.h"
#import "UIColor+XDHex.h"
#import "FIPTcpSocket.h"
#import "MBProgressHUD+XDPrompt.h"

@interface FIPTemperatureVC ()<FIPTcpSocketDelegate>
@property (weak, nonatomic) IBOutlet UIButton *ledBtn;

@property (weak, nonatomic) IBOutlet UIView *brightnessBgView;
@property (weak, nonatomic) IBOutlet UIView *colorBgView;
@property (weak, nonatomic) IBOutlet UIView *speedBgView;

@property (weak, nonatomic) IBOutlet UISlider *brightnessSlider;
@property (weak, nonatomic) IBOutlet UISlider *colorSlider;
@property (weak, nonatomic) IBOutlet UISlider *speedSlider;

@property (strong, nonatomic) FIPTcpSocket *refrshSocket;   //!< 回调使用的句柄
@property (strong, nonatomic) FIPTcpSocket *rgbOnSocket;
@property (strong, nonatomic) FIPTcpSocket *rgbSpeedSocket;
@property (strong, nonatomic) FIPTcpSocket *rgbRightSocket;
@property (strong, nonatomic) FIPTcpSocket *rgbColorSocket;

@end

//F3B457
static NSUInteger const kBorderColor = 0xF3B457;       // 边框颜色
static NSInteger  const kHudDelay = 0.5;               // HUD隐藏的时间

@implementation FIPTemperatureVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    
}

- (void)initSubViews {
    [self.ledBtn addTarget:self action:@selector(ledBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.brightnessBgView.layer.borderWidth = 1;
    self.brightnessBgView.layer.borderColor = [UIColor xd_colorWithHex:kBorderColor].CGColor;
    [self.brightnessSlider setThumbImage:[UIImage imageNamed:@"temp_slider_thumb"] forState:UIControlStateNormal];
    [self.brightnessSlider setThumbImage:[UIImage imageNamed:@"temp_slider_thumb"] forState:UIControlStateHighlighted];
    [self.brightnessSlider addTarget:self action:@selector(brightSlider:) forControlEvents:UIControlEventValueChanged];
    
    self.colorBgView.layer.borderWidth = 1;
    self.colorBgView.layer.borderColor = [UIColor xd_colorWithHex:kBorderColor].CGColor;
    [self.colorSlider setThumbImage:[UIImage imageNamed:@"temp_slider_thumb"] forState:UIControlStateNormal];
    [self.colorSlider setThumbImage:[UIImage imageNamed:@"temp_slider_thumb"] forState:UIControlStateHighlighted];
    [self.colorSlider addTarget:self action:@selector(colorSlider:) forControlEvents:UIControlEventValueChanged];
    
    self.speedBgView.layer.borderWidth = 1;
    self.speedBgView.layer.borderColor = [UIColor xd_colorWithHex:kBorderColor].CGColor;
    [self.speedSlider setThumbImage:[UIImage imageNamed:@"temp_slider_thumb"] forState:UIControlStateNormal];
    [self.speedSlider setThumbImage:[UIImage imageNamed:@"temp_slider_thumb"] forState:UIControlStateHighlighted];
    [self.speedSlider addTarget:self action:@selector(speedSlider:) forControlEvents:UIControlEventValueChanged];
    
    // 请求同步数据
    [self requestSyncData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - FIPTcpSocketDelegate
- (void)fIPTcpSocket:(FIPTcpSocket *)socket successWithData:(NSData *)data {
    NSLog(@"请求成功: %@", data);
}
- (void)fIPTcpSocket:(FIPTcpSocket *)socket failedWithError:(NSError *)error {
    NSLog(@"请求失败: %@", error);
}

#pragma mark - event response
- (void)ledBtnTapped:(UIButton *)btn {
    btn.selected = !btn.selected;
    [self requestRGBWithL_On:btn.selected];
}

- (void)brightSlider:(UISlider *)slider {
    NSInteger bright = (NSInteger)(slider.value * 11);
    bright = (bright > 10) ? 10 : bright;
    NSLog(@"抬起时的值, %ld", (long)bright);
    [self requestRGBWithL_Bright:bright];
}

- (void)colorSlider:(UISlider *)slider {
    NSInteger mode; // 0-静态颜色 1-七彩渐变 2-七彩跳变
    NSInteger r = 0;
    NSInteger g = 0;
    NSInteger b = 0;
    
    NSInteger rA[7] = {226, 233, 244, 189, 35,  176, 20};
    NSInteger gA[7] = {32,  124, 233, 216, 162, 31,  121};
    NSInteger bA[7] = {38,  40,  43,  107, 221, 131, 188};
    
    if (slider.value < 1.0 / 3.0) {
        mode = 1;
    } else if (slider.value < 2.0 / 3.0) {
        mode = 0;
        NSInteger index = (NSInteger)((slider.value - 1.0 / 3.0) / (1.0 / 3.0) * 7.0);
        NSLog(@"color抬起时的index = %ld", (long)index);
        r = rA[index];
        g = gA[index];
        b = bA[index];
    } else {
        mode = 2;
    }
    
    [self requestRGBL_ColorWithMode:mode r:r g:g b:b];
}

- (void)speedSlider:(UISlider *)slider {
    NSInteger speed = (NSInteger)(slider.value * 11);
    speed = (speed > 10) ? 10 : speed;
    NSLog(@"抬起时的值, %ld", (long)speed);
    [self requestRGBWithL_Speed:speed];
}

#pragma mark - private methods
- (void)refreshWholeViewWithData:(NSData *)data {
    if (data.length != 21) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"同步数据错误"];
        return;
    }
    
    NSLog(@"同步成功接收到的数据: %@", data);
    
    for (NSInteger i = 0; i<21; i+=7) {
        Byte byte[7];
        [data getBytes:byte range:NSMakeRange(i, 7)];
        if ((byte[0] == 0xA5) && (byte[2] == 0x01)) {
            NSLog(@"加热状态 = %d", byte[3]);
        }
        if ((byte[0] == 0xA5) && (byte[2] == 0x02)) {
            NSLog(@"RGB状态, L_ON = %d, L_SPEED = %d, L_BRIGHT = %d", byte[3], byte[4], byte[5]);
            self.ledBtn.selected = byte[3];
            [self.speedSlider setValue:(byte[4] / 11.0 + 0.5 / 11.0) animated:YES];
            [self.brightnessSlider setValue:(byte[5] / 11.0 + 0.5 / 11.0) animated:YES];
        }
        if ((byte[0] == 0xA5) && (byte[2] == 0x03)) {
            NSLog(@"RGB模式, MODE = %d, R_VAL = %d, G_VAL = %d, B_VAL = %d", byte[3], byte[4], byte[5], byte[6]);
            [self refreshColorMode:byte[3] r:byte[4] g:byte[5] b:byte[6]];
        }
    }
}

- (void)refreshColorMode:(NSInteger)mode r:(NSInteger)r g:(NSInteger)g b:(NSInteger)b {
    NSInteger rA[7] = {226, 233, 244, 189, 35,  176, 20};
    NSInteger gA[7] = {32,  124, 233, 216, 162, 31,  121};
    NSInteger bA[7] = {38,  40,  43,  107, 221, 131, 188};
    
    NSInteger index = 0;
    for (NSInteger i = 0; i < 7; i++) {
        if ((rA[i] == r)
            && (gA[i] == g)
            && (bA[i] == b)) {
            index = i;
            break;
        }
    }
    
    float value = 0;
    if (mode == 0) {
        value = 1.0 / 3.0 + index / 3.0 / 7.0 + 1 / 3.0 / 7.0 / 2.0;
    }else if (mode == 1) {
        value = 1.0 / 6.0;              // 保证居中
    }else if (mode == 2) {
        value = 2.0 / 3.0 + 1.0 / 6.0;  // 保证居中
    }
    
    [self.colorSlider setValue:value animated:YES];
}

#pragma mark - network request
- (void)requestSyncData {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    Byte byte[4] = {0x01, 0x00, 0x00, 0x00};
    NSData *data = [NSData dataWithBytes:byte length:4];
    
    self.refrshSocket = [[FIPTcpSocket alloc] init];
    [self.refrshSocket sendToServerWithReqType:FIPRequestTypeSync dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
        [self refreshWholeViewWithData:data];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"界面刷新失败"];
    }];
}

- (void)requestRGBWithL_On:(BOOL)isOn {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    Byte l_on = isOn ? 0x01 : 0x00;
    Byte byte[4] = {l_on, 0x00, 0x00, 0x00};
    NSData *data = [NSData dataWithBytes:byte length:4];
    self.rgbOnSocket = [[FIPTcpSocket alloc] init];
    [self.rgbOnSocket sendToServerWithReqType:FIPRequestTypeModifyL_On dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"设置失败"];
        hud.completionBlock = ^(){
            [self requestSyncData];
        };
    }];
}

// birght的值空间[0, 10];
- (void)requestRGBWithL_Bright:(NSInteger)bright {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    Byte byte[4] = {bright, 0x00, 0x00, 0x00};
    NSData *data = [NSData dataWithBytes:byte length:4];
    self.rgbRightSocket = [[FIPTcpSocket alloc] init];
    [self.rgbRightSocket sendToServerWithReqType:FIPRequestTypeModifyL_Bright dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"设置失败"];
        hud.completionBlock = ^(){
            [self requestSyncData];
        };
    }];
}

// mode的值空间[0, 2];
- (void)requestRGBL_ColorWithMode:(NSInteger)mode r:(NSInteger)r g:(NSInteger)g b:(NSInteger)b {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    Byte byte[4] = {mode, r, g, b};
    NSData *data = [NSData dataWithBytes:byte length:4];
    self.rgbColorSocket = [[FIPTcpSocket alloc] init];
    [self.rgbColorSocket sendToServerWithReqType:FIPRequestTypeModifyMode dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"设置失败"];
        hud.completionBlock = ^(){
            [self requestSyncData];
        };
    }];
}

// birght的值空间[0, 10];
- (void)requestRGBWithL_Speed:(NSInteger)speed {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    Byte byte[4] = {speed, 0x00, 0x00, 0x00};
    NSData *data = [NSData dataWithBytes:byte length:4];
    self.rgbSpeedSocket = [[FIPTcpSocket alloc] init];
    [self.rgbSpeedSocket sendToServerWithReqType:FIPRequestTypeModifyL_Speed dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"设置失败"];
        hud.completionBlock = ^(){
            [self requestSyncData];
        };
    }];
}

#pragma mark - getters and setters
//- (FIPTcpSocket *)socket {
//    if (!_socket) {
//        _socket = [[FIPTcpSocket alloc] initWithDelegate:self];
//    }
//    return _socket;
//}

@end
